package com.learn.controller;

import com.learn.entities.PayDTO;
import com.learn.resp.Result;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @author DJJ_F
 * @version 1.0
 * @date 2025/07/31
 * @description ch03 基础工程
 * ch05 负载均衡
 */
@RestController
public class OrderController {
    public static final String PaymentSrv_URL = "http://cloud-payment-service";
    @Resource
    private RestTemplate restTemplate;

    @PostMapping("/consumer/pay/add")
    public Result addOrder(@RequestBody PayDTO payDTO) {
        return restTemplate.postForObject(PaymentSrv_URL + "/pay/add", payDTO, Result.class);
    }

    @DeleteMapping("/consumer/pay/del/{id}")
    public Result deletePayById(@PathVariable("id") Integer id) {
        return restTemplate.postForObject(PaymentSrv_URL + "/pay/del/" + id, id, Result.class);
    }
    @PutMapping("/consumer/pay/update")
    public Result updatePayById(@RequestBody PayDTO payDTO) {
        ResponseEntity<Result> exchange = restTemplate.exchange(
                PaymentSrv_URL + "/pay/update",
                HttpMethod.PUT,
                new HttpEntity<>(payDTO, new HttpHeaders()),
                Result.class
        );
        return exchange.getBody();
    }
    @GetMapping("/consumer/pay/get/{id}")
    public Result selectOneById(@PathVariable("id") Integer id) {
        return restTemplate.getForObject(PaymentSrv_URL + "/pay/get/" + id, Result.class, id);
    }

    @GetMapping("/consumer/info")
    public String getInfo() {
        return restTemplate.getForObject(PaymentSrv_URL + "/pay/info", String.class);
    }

    @Resource
    private DiscoveryClient discoveryClient;

    @GetMapping("/consumer/discovery")
    public String getDiscovery() {
        discoveryClient.getServices().forEach(System.out::println);

        System.out.println("==============");

        List<ServiceInstance> instances = discoveryClient.getInstances("cloud-payment-service");
        for (ServiceInstance instance : instances) {
            System.out.println(instance.getPort());
        }
        return "ok";
    }
}
